class Solution
{
public:
    int maxScore(vector<vector<int>> &grid)
    {
        int m = grid.size();
        int n = grid[0].size();

        vector<vector<int>> cornerMin(m, vector<int>(n, INT_MAX));
        cornerMin[0][0] = grid[0][0];
        for (int i = 1; i < m; i++)
        {
            cornerMin[i][0] = min(cornerMin[i - 1][0], grid[i][0]);
        }
        for (int j = 1; j < n; j++)
        {
            cornerMin[0][j] = min(cornerMin[0][j - 1], grid[0][j]);
        }
        for (int i = 1; i < m; i++)
        {
            for (int j = 1; j < n; j++)
            {
                cornerMin[i][j] = min({cornerMin[i - 1][j], cornerMin[i][j - 1], grid[i][j]});
            }
        }

        int result = INT_MIN;
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (i > 0)
                {
                    result = max(result, grid[i][j] - cornerMin[i - 1][j]);
                }
                if (j > 0)
                {
                    result = max(result, grid[i][j] - cornerMin[i][j - 1]);
                }
            }
        }
        return result;
    }
};